/**
 * 首页（资料）
 */
package com.xiaomuwu.android.ui.home

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.Fragment
import com.xiaomuwu.android.R
import com.xiaomuwu.android.XiaoMuWuApplication
import com.xiaomuwu.android.ui.ForSearch
import kotlinx.android.synthetic.main.res_fragment.*

class ResFragment:Fragment() {

////    private var adapter: ResAdapter=ResAdapter(this,viewModel.resList)    //check(error)
//    private lateinit var adapter: ResListAdapter

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.res_fragment,container,false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 还原标签搜索框输入的内容
        searchTagsEdit?.setText(if(ForSearch.forResTags==null){
            ""
        }else{
            ForSearch.forResTags
        })

        // 还原单选按钮选中状态
        when(ForSearch.resSortBy){
            "New"->{
                radio_new.isChecked=true
            }
            "DownCount"->{
                radio_count.isChecked=true
            }
        }
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        // 标签搜索框内容变化监听
        searchTagsEdit?.addTextChangedListener { editable ->

            // 更新标签搜索内容
            ForSearch.forResTags=if(editable?.isNotBlank()==true){
                editable.toString()
            }else{
                null
            }

            updateRes() // 刷新资料列表
        }

        // 单选按钮选中监听
        resRadioGroup?.setOnCheckedChangeListener { _, checkd ->
            // 更新排序方式
            when(checkd) {
                R.id.radio_new -> {
                    ForSearch.resSortBy="New"   // “最新”
                }
                R.id.radio_count -> {
                    ForSearch.resSortBy="DownCount" // “最多下载”
                }
            }

            updateRes() // 刷新资料列表
        }
    }

    override fun onPause() {
        super.onPause()
        ForSearch.forResTags = null    // 重置标签搜索内容
        ForSearch.resSortBy = "New" // 重置资料排序方式
    }

    /**
     * 刷新资料列表
     */
    private fun updateRes() {
        // 发送刷新资料列表广播
        val intent=Intent("com.xiaomuwu.android.UpdateRes")
        XiaoMuWuApplication.context.sendBroadcast(intent)
    }

}